package com.xinzhi.seckill.vo;

import com.xinzhi.seckill.utils.ValidatorUtil;
import com.xinzhi.seckill.validation.IsMoblie;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 手机号码校验规则
 */
//ConstraintValidator<IsMoblie,String>
//第一个为注解，第二个为注解的定义
public class IsMoblieValidation implements ConstraintValidator<IsMoblie,String> {

    private boolean required = false;


    @Override
    //初始化
    public void initialize(IsMoblie constraintAnnotation) {
        //是否必填
        required = constraintAnnotation.required();
    }

    @Override
    /**
     * 校验规则
     */
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if(required){
            return ValidatorUtil.isMobile(value);
        }else {
            if (StringUtils.isEmpty(value)){
                return true;
            }else {
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}
